<?php

/**
 * 
 * Some rights reserved：abc3210.com
 * Contact email:admin@abc3210.com
 */
class AttachmentsAction extends AdminbaseAction {

    //时间
    public $time;
    //上传用户
    public $upname;
    //上传用户ID
    public $upuserid;
    //上传模块
    public $module = "Contents";
    //上传栏目ID
    public $catid = 0;
    // 上传日期目录
    public $dateFormat = "Y/m";
    //附件存在物理地址
    public $path = "";
    //附件临时编号
    public $filepass;
    //上传成功以后，完整附件物理地址
    public $filepath;
    //上传成功以后，完整的网络地址
    public $filehttp;

    function _initialize() {

        $this->isadmin = session(C("USER_AUTH_KEY")) ? true : false;

        //以下权限，不参与后台的RBAC权限认证，使用前台的权限认证
        if (in_array(ACTION_NAME, array("swfupload", "upload", "swfupload_json_del", "swfupload_json", "getRemoteImage", "imageManager", "snapImgUp", "imageUp", "getMovie", "album_load", "crop_upload"))) {
            C("USER_AUTH_ON", false);
            parent::_initialize();
            //除了swfupload是用post数据验证权限外，其他的必须验证是否登陆
            if ("swfupload" != ACTION_NAME) {
                if (empty($this->Cache['uid']) || $this->Cache['uid'] <= 0) {
                    $this->assign("jumpUrl", C('USER_AUTH_GATEWAY'));
                    $this->error("请登陆后操作！");
                }
            }
        } else {
            //恢复权限认证
            C("USER_AUTH_ON", true);
            parent::_initialize();
        }
        import('@.ORG.Util.UploadFile');

        $this->initUser();
        //当前登陆用户名
        $this->upuserid = $this->Cache['uid'];
        //附件目录强制/d/file/ 后台设置的附件目录，只对网络地址有效
        $this->path = SITE_PATH . "/d/file/";

        $this->time = time();
    }

    /**
     * 附件管理 
     */
    public function index() {
        $db = M("Attachment");
        $where = array();
        $filename = $this->_get('filename');
        empty($filename) ? "" : $where['filename'] = array('like', '%' . $filename . '%');
        //时间范围搜索
        $start_uploadtime = $this->_get('start_uploadtime');
        $end_uploadtime = $this->_get('end_uploadtime');
        if (!empty($start_uploadtime)) {
            $where['_string'] = 'uploadtime >= ' . strtotime($start_uploadtime) . ' AND uploadtime <= ' . strtotime($end_uploadtime) . '';
        }
        $fileext = $this->_get('fileext');
        empty($fileext) ? "" : $where['fileext'] = array('eq', $fileext);
        //附件使用状态
        $status = $this->_get('status');
        $status == "" ? "" : $where['status'] = array('eq', $status);

        $count = $db->where($where)->count();
        $page = $this->page($count, 20);
        $data = $db->where($where)->limit($page->firstRow . ',' . $page->listRows)->order(array("uploadtime" => "DESC"))->select();

        foreach ($data as $k => $v) {
            $data[$k]['uploadtime'] = date("Y-m-d H:i:s", $data[$k]['uploadtime']);
            $data[$k]['filesize'] = round($data[$k]['filesize'] / 1024, 2);
            $data[$k]['thumb'] = glob(dirname($this->path . $data[$k]['filepath']) . '/thumb_*' . basename($data[$k]['filepath']));
        }
        $this->assign("category", F("Category"));
        $this->assign("filename", $filename);
        $this->assign("start_uploadtime", $start_uploadtime);
        $this->assign("end_uploadtime", $end_uploadtime);
        $this->assign("fileext", $fileext);
        $this->assign("data", $data);
        $this->assign("Page", $page->show('Admin'));
        $this->display();
    }

    /**
     * 删除附件 get单个删除 post批量删除 
     */
    public function delete() {
        import('@.ORG.Util.Attachment');
        if ($this->isPost()) {
            $aid = $_POST['aid'];
            $Attachment = new Attachment();
            $Attachment->path($this->path);
            foreach ($aid as $k => $v) {
                $Attachment->del($v);
            }
            $status = true;
        } else {
            $aid = $this->_get('aid');
            if (empty($aid)) {
                $this->error("缺少参数！");
            }
            $Attachment = new Attachment();
            $Attachment->path($this->path);
            $status = $Attachment->del($aid);
        }
        if ($this->isAjax()) {
            if ($status) {
                $this->ajaxReturn("", "删除附件成功！", true);
            } else {
                $this->ajaxReturn("", "删除附件失败！", false);
            }
        } else {
            if ($status) {
                $this->success("删除附件成功！");
            } else {
                $this->error("删除附件失败！");
            }
        }
    }

    /**
     * 常规上传 
     */
    public function upload() {
        
    }

    /**
     * swfupload 上传 
     * 通过swf上传成功以后回调处理时会调用swfupload_json方法增加cookies！
     */
    public function swfupload() {
        if ($this->isPost()) {

            $isadmin = $this->_post("isadmin");
            //验证上传密钥串
            $key = authcode($this->_post("swf_auth_key"), "DECODE", C("AUTHCODE"));
            $this->upuserid = (int) $key;

            if (empty($key) || $key != $this->_post("userid")) {
                exit("0,你没有权限！");
            }

            $this->catid = $this->_post("catid");
            $this->module = strtolower($this->_post("module"));
            $authkey = explode(",", authcode($this->_post("authkey"), "DECODE", C("AUTHCODE")));

            $upload = new UploadFile();

            //参数补充完整
            if (empty($authkey[1])) {
                //如果允许上传的文件类型为空，启用网站配置的 uploadallowext
                if ($isadmin) {
                    $authkey[1] = CONFIG_UPLOADALLOWEXT;
                } else {
                    $authkey[1] = CONFIG_QTUPLOADALLOWEXT;
                }
            }

            //检查用户是否有上传权限
            //设置上传类型
            $upload->allowExts = explode("|", $authkey[1]);

            //设置上传大小
            if ($isadmin) {
                $upload->maxSize = (int) CONFIG_UPLOADMAXSIZE * 1024; //单位字节
            } else {
                //前台
                $upload->maxSize = (int) CONFIG_QTUPLOADMAXSIZE * 1024; //单位字节
            }
            //图片裁减相关设置，如果开启，将不保留原图
            if (!empty($authkey[3]) && !empty($authkey[4])) {
                $upload->thumb = true;
                $upload->thumbRemoveOrigin = true;
            }
            //设置缩略图最大宽度
            $upload->thumbMaxWidth = $authkey[3];
            //设置缩略图最大高度
            $upload->thumbMaxHeight = $authkey[4];

            //上传目录 可以单独写个方法，根据栏目ID生成相对于栏目目录附件
            $this->filepath = $upload->savePath = $this->FilePath();

            //开始上传
            if ($upload->upload()) {
                //上传成功
                $info = $upload->getUploadFileInfo();
                $status = $this->FileData($info[0]);
                //是否添加水印
                if ($authkey[5]) {
                    
                }
                if ($status) {
                    if (in_array($info[0]['extension'], array("jpg", "png", "jpeg", "gif"))) {
                        // 附件ID 附件网站地址 图标(图片时为1) 文件名
                        echo "$status," . $this->filehttp . ",1," . str_replace(array("\\", "/"), "", $info[0]['name']);
                        exit;
                    } else {
                        $fileext = $info[0]['extension'];
                        if ($fileext == 'zip' || $fileext == 'rar')
                            $fileext = 'rar';
                        elseif ($fileext == 'doc' || $fileext == 'docx')
                            $fileext = 'doc';
                        elseif ($fileext == 'xls' || $fileext == 'xlsx')
                            $fileext = 'xls';
                        elseif ($fileext == 'ppt' || $fileext == 'pptx')
                            $fileext = 'ppt';
                        elseif ($fileext == 'flv' || $fileext == 'swf' || $fileext == 'rm' || $fileext == 'rmvb')
                            $fileext = 'flv';
                        else
                            $fileext = 'do';

                        echo "$status," . $this->filehttp . "," . $fileext . "," . str_replace(array("\\", "/"), "", $info[0]['name']);
                        exit;
                    }
                } else {
                    //删除已经上传的图片，这里逻辑还要优化
                    @unlink($this->filepath);
                    exit("0,上传成功，但写库失败！");
                }
            } else {
                //上传失败，返回错误
                exit("0," . $upload->getErrorMsg());
            }
        } else {
            if ($this->upuserid <= 0) {
                $this->error("请登陆后再操作！");
            }
            //1,允许上传的文件类型,是否允许从已上传中选择,图片高度,图片高度,是否添加水印1是
            $args = $this->_get('args');

            $authkey = $this->_get('authkey');
            $field = $this->_get('field');

            if (empty($args) || $args != authcode($authkey, "DECODE", C("AUTHCODE"))) {
                $this->error("配置参数有误！");
            }
            $info = explode(",", $args);
            $this->catid = $this->_get('catid');

            $att_not_used = $this->cookie('att_json');
            if (empty($att_not_used))
                $tab_status = ' class="on"';
            if (!empty($att_not_used))
                $div_status = ' hidden';

            //参数补充完整
            if (empty($info[1])) {
                //如果允许上传的文件类型为空，启用网站配置的 uploadallowext
                if ($this->isadmin) {
                    $info[1] = CONFIG_UPLOADALLOWEXT;
                } else {
                    $info[1] = CONFIG_QTUPLOADALLOWEXT;
                }
            }

            //获取临时未处理的图片
            $att = $this->att_not_used();
            //var_dump($att);exit;
            $this->assign("initupload", initupload($this->module, $this->catid, $args, $this->upuserid, "8", $this->isadmin));
            //上传格式显示
            $this->assign("file_types", implode(",", explode("|", $info[1])));
            $this->assign("file_size_limit", $this->isadmin ? CONFIG_UPLOADMAXSIZE : CONFIG_QTUPLOADMAXSIZE);
            $this->assign("file_upload_limit", (int) $info[0]);
            $this->assign("att", $att);
            $this->assign("tab_status", $tab_status);
            $this->assign("div_status", $div_status);
            $this->assign("att_not_used", $att_not_used);
            $this->display();
        }
    }

    /**
     * 加载图片库 
     */
    public function album_load() {
        $where = array();
        $db = M("Attachment");
        $filename = $this->_get("filename");
        $args = $this->_get("args");
        $args = explode(",", $args);
        empty($filename) ? "" : $where['filename'] = array('like', '%' . $filename . '%');
        $uploadtime = $this->_get("uploadtime");
        if (!empty($uploadtime)) {
            $start_uploadtime = strtotime($uploadtime . ' 00:00:00');
            $stop_uploadtime = strtotime($uploadtime . ' 23:59:59');
            $where['_string'] = 'uploadtime >= ' . $start_uploadtime . ' AND uploadtime <= ' . $stop_uploadtime . '';
        }
        //强制只是图片类型
        $where['isimage'] = array("eq", 1);

        $count = $db->where($where)->count();
        //启用分页
        $page = $this->page($count, 8);
        $data = $db->where($where)->order(array("uploadtime" => "DESC"))->limit($page->firstRow . ',' . $page->listRows)->select();
        foreach ($data as $k => $v) {
            $data[$k]['filepath'] = CONFIG_SITEFILEURL . $data[$k]['filepath'];
        }
        //var_dump($data);exit;
        $this->assign("Page", $page->show('Admin'));
        $this->assign("data", $data);
        $this->assign("file_upload_limit", $args[0]);
        unset($db);
        $this->display();
    }

    /**
     * 图片在线裁减，保存图片 
     */
    public function crop_upload() {
        $Prefix = "thumb_"; //默认裁减图片前缀
        $this->module = "contents";
        if (isset($GLOBALS["HTTP_RAW_POST_DATA"])) {
            $pic = $GLOBALS["HTTP_RAW_POST_DATA"];
            if (isset($_GET['width']) && !empty($_GET['width'])) {
                $width = intval($_GET['width']);
            }
            if (isset($_GET['height']) && !empty($_GET['height'])) {
                $height = intval($_GET['height']);
            }
            if (isset($_GET['file']) && !empty($_GET['file'])) {
                if (is_image($_GET['file']) == false)
                    exit();
                $file = $_GET['file'];
                $basename = basename($file);
                if (strpos($basename, $Prefix) !== false) {
                    $file_arr = explode('_', $basename);
                    $basename = array_pop($file_arr);
                }
                $new_file = $Prefix . $width . '_' . $height . '_' . $basename;

                //栏目ID
                $this->catid = intval($_GET['catid']);

                //附件访问目录地址，支持http开头
                $filepath = $this->Config['sitefileurl'];
                //存放地址，不包含附件目录
                $servaname = str_replace($this->path, "", $this->FilePath());
                //附件HTTP地址
                $filehttp = $filepath . $this->module . "/" . $servaname;
                //附件原始名称
                $filename = basename($_GET['file']);

                //附件保存后的名称
                $filesavename = str_replace(array("\\", "/"), "", $new_file);

                //上传文件的后缀类型
                $fileextension = fileext($_GET['file']);
                //设置为缩图
                $this->isthumb = 1;

                //保存图片
                file_put_contents($this->FilePath() . "/" . $new_file, $pic);
                //FTP远程附件
                if ((int) $this->Config['ftpstatus']) {
                    $imgpth = $this->FilePath() . "/" . $new_file;
                    import('@.ORG.Util.Ftp');
                    $this->Ftp = new Ftp();
                    $this->Ftp->connect($this->Config['ftphost'], $this->Config['ftpuser'], $this->Config['ftppassword'], $this->Config['ftpport'], $this->Config['ftppasv'], $this->Config['ftpssl'], $this->Config['ftptimeout']);
                    $remote = $this->Config['ftpuppat'] . str_replace(SITE_PATH."/", "", $imgpth);
                    $this->Ftp->put($remote, $imgpth);
                    unlink($imgpth);
                    $this->Ftp->close();
                }

                $infos = array(
                    "filepath" => $filepath,
                    "servaname" => $servaname,
                    "filehttp" => $filehttp,
                    "filename" => $filename,
                    "filesize" => filesize($this->FilePath() . "/" . $new_file),
                    "fileextension" => $fileextension,
                    "filesavename" => $filesavename,
                    "filehash" => md5($this->FilePath() . "/" . $new_file)
                );
            } else {

                return false;
            }
            echo $filepath . $servaname . "/" . $filesavename;
            exit;
        }
    }

    /**
     * 显示附件下的缩图
     */
    public function pullic_showthumbs() {
        $aid = $this->_get("aid");
        $info = M("Attachment")->where(array('aid' => $aid))->find();
        if ($info) {
            $infos = glob(dirname($this->path . $info['filepath']) . '/thumb_*' . basename($info['filepath']));
            foreach ($infos as $n => $thumb) {
                $thumbs[$n]['thumb_url'] = str_replace($this->path, CONFIG_SITEFILEURL, $thumb);
                $thumbinfo = explode('_', basename($thumb));
                $thumbs[$n]['thumb_filepath'] = $thumb;
                $thumbs[$n]['width'] = $thumbinfo[1];
                $thumbs[$n]['height'] = $thumbinfo[2];
            }
        }

        $show_header = 1;
        $this->assign("show_header", $show_header);
        $this->assign("thumbs", $thumbs);
        $this->display();
    }

    /**
     * 删除附件缩图 
     */
    public function pullic_delthumbs() {
        $filepath = urldecode($this->_get("filepath"));
        $reslut = @unlink($filepath);
        if ($reslut)
            exit('1');
        exit('0');
    }

    /**
     * 设置upload上传的json格式cookie 
     */
    protected function upload_json($aid, $src, $filename) {
        $arr['aid'] = $aid;
        $arr['src'] = trim($src);
        $arr['filename'] = urlencode($filename);
        $json_str = json_encode($arr);
        $att_arr_exist = $this->cookie('att_json');
        $att_arr_exist_tmp = explode('||', $att_arr_exist);
        if (is_array($att_arr_exist_tmp) && in_array($json_str, $att_arr_exist_tmp)) {
            return true;
        } else {
            $json_str = $att_arr_exist ? $att_arr_exist . '||' . $json_str : $json_str;
            $this->cookie('att_json', $json_str);
            return true;
        }
    }

    /**
     * 设置swfupload上传的json格式cookie 
     */
    public function swfupload_json() {
        $arr = array();
        $arr['aid'] = intval($_GET['aid']);
        $arr['src'] = trim($_GET['src']);
        $arr['filename'] = urlencode($_GET['filename']);
        return $this->upload_json($arr['aid'], $arr['src'], $arr['filename']);
    }

    /**
     * 删除swfupload上传的json格式cookie 
     */
    public function swfupload_json_del() {
        $arr['aid'] = intval($_GET['aid']);
        $arr['src'] = trim($_GET['src']);
        $arr['filename'] = urlencode($_GET['filename']);
        $json_str = json_encode($arr);
        $att_arr_exist = $this->cookie('att_json');
        $this->cookie('att_json', NULL);
        $att_arr_exist = str_replace(array($json_str, '||||'), array('', '||'), $att_arr_exist);
        $att_arr_exist = preg_replace('/^\|\|||\|\|$/i', '', $att_arr_exist);
        $this->cookie('att_json', $att_arr_exist);
        var_dump($this->cookie('att_json'));
    }

    /**
     * 获取临时未处理的图片 
     */
    protected function att_not_used() {
        $db = M("Attachment");
        //获取临时未处理文件列表
        $att_json = $this->cookie('att_json');
        if ($att_json) {
            if ($att_json) {
                $att_cookie_arr = explode('||', $att_json);
            }
            foreach ($att_cookie_arr as $_att_c)
                $att[] = json_decode($_att_c, true);
            if (is_array($att) && !empty($att)) {
                foreach ($att as $n => $v) {
                    $ext = fileext($v['src']);
                    if (in_array($ext, array('jpg', 'gif', 'png', 'bmp', 'jpeg'))) {
                        $att[$n]['fileimg'] = $v['src'];
                        $att[$n]['width'] = '80';
                        $att[$n]['filename'] = urldecode($v['filename']);
                    } else {
                        $att[$n]['fileimg'] = file_icon($v['src']);
                        $att[$n]['width'] = '64';
                        $att[$n]['filename'] = urldecode($v['filename']);
                    }
                    $this->cookie_att .= '|' . $v['src'];
                }
            }
        }
        unset($db);
        return $att;
    }

    /**
     * 保存上传成功后的信息到数据库
     * @param type $info 
     */
    protected function FileData($info) {
        if (!is_array($info)) {
            return false;
        }

        //附件访问目录地址，支持http开头
        $filepath = $this->Config['sitefileurl'];
        //存放地址，不包含附件目录
        $servaname = str_replace($this->path, "", $info['savepath']);
        //附件HTTP地址
        $filehttp = $filepath . $this->module . "/" . $servaname . $info['savename'];
        //附件原始名称
        $filename = $info['name'];

        //附件保存后的名称
        $filesavename = str_replace(array("\\", "/"), "", $info['savename']);
        //上传的文件大小
        $filesize = $info['size'];
        //上传文件的MIME类型
        $filetype = $info['type'];
        //上传文件的后缀类型
        $fileextension = $info['extension'];
        //上传文件的hash验证字符串
        $filehash = $info['hash'];

        $infos = array(
            "filepath" => $filepath,
            "servaname" => $servaname,
            "filehttp" => $filehttp,
            "filename" => $filename,
            "filesize" => $filesize,
            "filetype" => $filetype,
            "fileextension" => $fileextension,
            "filesavename" => $filesavename,
            "filehash" => $filehash
        );

        //保存上传后的物理地址
        $this->filepath .= "/" . $filesavename;
        $this->filehttp = CONFIG_SITEFILEURL . $servaname . "/" . $filesavename;

        return D("Attachment")->FileData($this->upuserid, $this->catid, $this->module, $infos, $this->isthumb);
    }

    /**
     * 取得文件保存路径
     * @param type $catid 栏目ID，当为0的时候，直接使用模块目录
     */
    protected function FilePath() {

        $path = $this->path . $this->module . "/" . date($this->dateFormat, $this->time);

        //检测目录是否存在，不存在创建
        if (!is_dir($path)) {
            if (!mk_dir($path, 0777)) {
                $this->error("创建目录失败！");
            }
        }

        return $path;
    }

    /**
     * 图片加水印 
     * source（必须）：原图文件名。
      Water（必须）：水印图片文件名
      savename（可选）：要保存的图片名，如果留空则用source
      alpha（可选）：水印图片的alpha值，默认为80，范围为0~100
     */
    protected function water($source, $water = "", $savename = null, $alpha = 80) {
        
    }

}

?>
